<template>
    <view>
        <view class="box flex-center" style="line-height: 1;" :style="imgStyle">
            <text class="item" v-if="hour">{{(hour)}}</text>
            <text v-if="hour">:</text>
            <text class="item">{{(minu)}}</text>
            <text>:</text>
            <text class="item">{{(sizes)}}</text>
        </view>
    </view>
</template>

<script setup>
import { onLoad, onShow, onBackPress, onHide } from "@dcloudio/uni-app"
import {ref,computed, watch, onBeforeUnmount} from 'vue'	

const props =  defineProps({
	size:{
		type: [String, Number],
		default:'16'
	},
    time: {
        type: [String, Number],
		default:'0'
    },
    // 是否倒叙计时
    flash: {
        type: Boolean,
        default: true
    },
	continue: {
		type: Boolean,
		default: true
	}
})

const emit = defineEmits(['timeFun', 'onInterval'])

const getHour = (timebind) => {
    return parseInt(timebind / 60 / 60) < 10 ? '0' + parseInt(timebind / 60 / 60) : parseInt(timebind / 60 / 60)
}
const getMinu = (timebind) => {
    return parseInt(((timebind / 60)) % 60) < 10 ? '0' + parseInt(((timebind / 60)) % 60) : parseInt(((timebind / 60)) % 60)
}
const getSice = (timebind) => {
    return parseInt((timebind % 60)) < 10 ? '0' + parseInt((timebind % 60)) : parseInt((timebind % 60))
}

const imgStyle = computed(() => {
	let style = {}
    style.fontSize = props.size + 'rpx'
	return style;
})

const hour = ref(0)
const minu = ref(0)
const sizes = ref(0)

const times = ref(0)
const timer = ref(null)


const setTime = () => {
	hour.value = times.value >= 3600 ? getHour(times.value) : 0;
	minu.value = getMinu(times.value);
	sizes.value = getSice(times.value);
	emit('onInterval', times.value);
};

const initFun = () => {
    clearInterval(timer.value)
	if (!props.continue) {
		setTime();
		return;
	};
	
    timer.value = setInterval(() => {
        if(props.flash){
            times.value--
        } else{
            times.value++
        }
       
		setTime();
        if(times.value <= 0){
            clearInterval(timer.value)
            emit('timeFun', 1)
        }
    }, 1000)
}
initFun()

onHide(() => {
	clearInterval(timer.value)
})

onBeforeUnmount(() => {
	clearInterval(timer.value)
})
watch(
    () => props.time, (newVal, oldVal) => {
        if(newVal){
            times.value = newVal
            initFun()
        }
    }, {
        immediate: true,
        deep: true
    }
)

const superpositionTime = time => {
	 times.value += time;
};

defineExpose({ times, initFun, superpositionTime })


</script>

<style lang="scss" scoped>
.box span{margin: 0 5px; font-weight: bold;}
</style>